
import 'package:hongsheng/api/SPClassApiManager.dart';
import 'package:hongsheng/api/SPClassHttpCallBack.dart';
import 'package:hongsheng/app/SPClassApplicaion.dart';
import 'package:hongsheng/model/SPClassSchemeDetailEntity.dart';
import 'package:hongsheng/model/SPClassUserTaskList.dart';
import 'package:hongsheng/pages/common/SPClassDialogUtils.dart';
import 'package:hongsheng/pages/competition/scheme/SPClassSchemeDetailPage.dart';
import 'package:hongsheng/pages/user/SPClassRechargeDiamondPage.dart';
import 'package:hongsheng/utils/SPClassCommonMethods.dart';
import 'package:hongsheng/utils/SPClassImageUtil.dart';
import 'package:hongsheng/utils/SPClassNavigatorUtils.dart';
import 'package:hongsheng/utils/SPClassToastUtils.dart';
import 'package:hongsheng/utils/colors.dart';
import 'package:hongsheng/widgets/SPClassTaskToast.dart';
import 'package:flutter/material.dart';
// import 'package:flutter_pangle_ads/flutter_pangle_ads.dart';

import 'SPClassPrizeDrawPage.dart';

class SPClassTaskPage extends StatefulWidget {
  const SPClassTaskPage({Key ?key}) : super(key: key);

  @override
  _SPClassTaskPageState createState() => _SPClassTaskPageState();
}

class _SPClassTaskPageState extends State<SPClassTaskPage> {
  List<SPClassUserTask> spProMsgList =[];
  var myEventBus;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getTask();
    // FlutterPangleAds.showRewardVideoAd(
    //     '948840227',
    //     customData: 'customData',
    //     userId: SPClassApplicaion.spProUserLoginInfo?.spProUserId.toString(),
    //     type: 'preLoad'
    // );
    myEventBus=SPClassApplicaion.spProEventBus.on<String>().listen((event) {//人物头部
      if(event=="task:refresh"){
        getTask();
        setState(() {});
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return dayTaskWidget();
  }

  Widget dayTaskWidget(){
    return Container(
      padding: EdgeInsets.only(left: width(12),right: width(12),top: width(14)),
      child: Column(
        children: <Widget>[
          Row(
            children: <Widget>[
              Container(
                width: height(4),
                height: height(14),
                decoration: BoxDecoration(
                    color: Color(0xFFDE3C31),
                    borderRadius: BorderRadius.circular(100)
                ),
              ),
              SizedBox(width: 4,),
              Text("每日任务",style: TextStyle(fontWeight: FontWeight.w600,fontSize: sp(15)),),
              SizedBox(width: 4,),
              Text("赚取积分，兑好礼",style: TextStyle(fontSize: sp(12),color: MyColors.grey_99,height: 2),),
            ],
          ),
          SizedBox(height: width(12),),
          Container(
            padding: EdgeInsets.symmetric(horizontal: width(17),),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(8),
              boxShadow:[
                BoxShadow(
                  offset: Offset(0,0),
                  color: Color(0xFF000000).withOpacity(0.16),
                  blurRadius:width(6,),),
              ],
            ),
            child: Column(
              children: spProMsgList.map((e){
                return Container(
                  margin: EdgeInsets.symmetric(vertical: width(14)),
                  child: Row(
                    children: <Widget>[
                      Image.asset(
                        SPClassImageUtil.spFunGetImagePath(
                            getIcon(e.spProTaskName!)),
                        width: width(31),
                      ),
                      SizedBox(width: width(8),),
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Row(
                              children: <Widget>[
                                RichText(
                                  text: TextSpan(
                                      text: '${e.spProTaskName}',
                                      style: TextStyle(fontSize: sp(13),color: MyColors.grey_33),
                                      children: [
                                        TextSpan(
                                          text: e.spProTaskName=='钻石充值'?'':' +${double.parse(e.spProPoints!).toStringAsFixed(0)}',
                                          style: TextStyle(fontSize: sp(15),color: MyColors.main1,fontWeight: FontWeight.bold),
                                        ),
                                      ]
                                  ),
                                ),
                                Visibility(
                                  child: Container(
                                    child: Image.asset(
                                      SPClassImageUtil.spFunGetImagePath('ic_hot',),
                                      width: width(27),
                                    ),
                                    margin: EdgeInsets.only(left: width(2)),
                                  ),
                                  visible: e.spProTaskName=='钻石充值',
                                )
                              ],
                            ),

                            Text('${e.spProDescribe}',style: TextStyle(fontSize: sp(12),color: MyColors.grey_99),),
                          ],
                        ),
                      ),
                      SizedBox(width: width(25),),
                      GestureDetector(
                        child: Column(
                          children: <Widget>[
                            Container(
                              width: width(58),
                              height: width(20),
                              alignment: Alignment.center,
                              decoration: BoxDecoration(
                                  border: Border.all(color: Color(0xFF707070),width: 0.6),
                                  // border: Border.all(color: e.spProCanReceive=='1'?Colors.red:e.spProIsReceive=='1'?MyColors.grey_cc: Color(0xFF707070),width: 0.6),
                                  borderRadius: BorderRadius.circular(150),
                                  color: Colors.white
                                  // color: e.spProCanReceive=='1'?Colors.red:e.spProIsReceive=='1'?MyColors.grey_cc:Colors.white
                              ),
                              child: Text('${getText(e.spProTaskName!)}',style: TextStyle(fontSize: sp(12),color:MyColors.grey_33),),
                              // child: Text(e.spProCanReceive=='1'?'领取':e.spProIsReceive=='1'?'已领取':'${getText(e.spProTaskName)}',style: TextStyle(fontSize: sp(12),color:  e.spProCanReceive=='1'?Colors.white:e.spProIsReceive=='1'?MyColors.grey_99:MyColors.grey_33),),
                            ),
                          ],
                        ),
                        behavior: HitTestBehavior.translucent,
                        onTap: (){
                          // if(e.spProCanReceive=='1'){
                          //   SPClassApiManager.spFunGetInstance().spFunGetUserReceiveTasks(context:context,params: {'task_key':e.spProTaskKey},spProCallBack:SPClassHttpCallBack(
                          //       spProOnSuccess: (result){
                          //         e.spProCanReceive ='0';
                          //         e.spProIsReceive ='1';
                          //         SPClassToastUtils.spFunShowToast(msg: '领取成功');
                          //         SPClassApplicaion.spFunGetUserInfo();
                          //         setState(() {
                          //         });
                          //       }
                          //   ));
                          //   return;
                          // }
                          // if(e.spProIsReceive=='1'){
                          //   return;
                          // }
                          onClick(e);
                        },
                      )
                    ],
                  ),
                );
              }).toList(),
            ),
          )
        ],
      ),
    );
  }


  Future getTask() async{
    SPClassApiManager.spFunGetInstance().spFunGetUserTasks<SPClassUserTaskList>(spProCallBack:SPClassHttpCallBack(
        spProOnSuccess: (result){
          spProMsgList=result.spProTaskList!;
          setState(() {
          });
        }
    ));
  }

  getIcon(String title){
    String icon ='';
    switch(title){
      case '钻石充值':icon ='ic_task_zuanshi';break;
      case '幸运大转盘':icon ='ic_task_zhuanpan';break;
      case '查看方案':
      case '查看免费方案':
      case '查看付费方案':
        icon ='ic_task_look';break;
      case '分享方案':icon ='ic_task_share';break;
      case '关注方案':icon ='ic_task_guanzhufangan';break;
      case '关注专家':icon ='ic_task_guanzhuzhuanjia';break;
      case '每日观看视频':icon ='ic_video';break;
    }
    return icon;
  }

  getText(String title){
    String text ='';
    switch(title){
      case '钻石充值':text ='去充值';break;
      case '幸运大转盘':text ='去参与';break;
      case '查看方案':
      case '查看免费方案':
      case '查看付费方案':
      text ='去查看';break;
      case '分享方案':text ='去分享';break;
      case '关注方案':
      case '关注专家':text ='去关注';break;
      case '每日观看视频':text ='去观看';break;
    }
    return text;
  }

  onClick(SPClassUserTask data){
    String title =data.spProTaskName!;
    if(title=='钻石充值'){
      SPClassNavigatorUtils.spFunPushRoute(
          context,
          SPClassRechargeDiamondPage()
      );
    }
    if(title=='幸运大转盘'){
      SPClassNavigatorUtils.spFunPushRoute(
          context,
          SPClassPrizeDrawPage()
      );
    }
    if(title=='查看方案'||title =='查看免费方案'||title =='查看付费方案'){
      SPClassApiManager.spFunGetInstance().spFunSchemeRecommended(
          queryParameters: {"scheme_id":''},
          context: context,spProCallBack:SPClassHttpCallBack<SPClassSchemeDetailEntity>(
          spProOnSuccess: (value){
            if(value.spProTask!=null&&value.spProTask?.spProIsShow=='1'){
              SPClassTaskToast.spFunToast(context,value.spProTask!);
            }
            SPClassNavigatorUtils.spFunPushRoute(context,  SPClassSchemeDetailPage(value));
          }
      ));
      // SPClassNavigatorUtils.spFunPopAll(context);
      // SPClassApplicaion.spProEventBus.fire("tab:home");
    }
    if(title=='分享方案'){
      SPClassNavigatorUtils.spFunPopAll(context);
      SPClassApplicaion.spProEventBus.fire("tab:home");
    }
    if(title=='关注方案'){
      SPClassNavigatorUtils.spFunPopAll(context);
      SPClassApplicaion.spProEventBus.fire("tab:home");
    }
    if(title=='关注专家'){
      SPClassNavigatorUtils.spFunPopAll(context);
      SPClassApplicaion.spProEventBus.fire("tab:expert");
    }
    // if(title=='每日观看视频'){
    //   bool isSuccess =false;
    //   bool isLoading =true;
    //   if(data.spProComplete=='5'){
    //     SPClassToastUtils.spFunShowToast(msg: '每天最多观看5次');
    //     return;
    //   }
    //   SPClassDialogUtils.spFunShowLoadingDialog(context,barrierDismissible: true,content:"加载中",dismiss: (){
    //     isLoading =false;
    //   });
    //   FlutterPangleAds.onEventListener((event) {
    //     // 普通广告事件
    //     String _adEvent = 'adId:${event.adId} action:${event.action}';
    //     if (event is AdErrorEvent) {
    //       // 错误事件
    //       _adEvent += ' errCode:${event.errCode} errMsg:${event.errMsg}';
    //       if(isLoading){
    //         Navigator.of(context).pop();
    //       }
    //     } else if (event is AdRewardEvent) {
    //       // 激励事件
    //       _adEvent +=
    //       ' rewardVerify:${event.rewardVerify} rewardAmount:${event.rewardAmount} rewardName:${event.rewardName} errCode:${event.errCode} errMsg:${event.errMsg} customData:${event.customData} userId:${event.userId}';
    //     }
    //     if (event.action == AdEventAction.onAdExposure ) {
    //       if(isLoading){
    //         Navigator.of(context).pop();
    //       }
    //     }
    //     if (event.action == AdEventAction.onAdClosed ) {
    //       _adEvent += '关闭广告';
    //       if(isSuccess){
    //         SPClassToastUtils.spFunShowToast(msg: '奖励领取成功');
    //         getTask();
    //         SPClassApplicaion.spFunGetUserInfo();
    //       }
    //
    //     }
    //     if (event.action == AdEventAction.onAdSkip ) {
    //       _adEvent += '跳过广告';
    //     }
    //     if (event.action == AdEventAction.onAdComplete ) {
    //       _adEvent += '完成广告';
    //     }
    //     if (event.action == AdEventAction.onAdReward ) {
    //       isSuccess= true;
    //       _adEvent += '领取奖励';
    //     }
    //     print('onEventListener:$_adEvent');
    //   });
    //   FlutterPangleAds.showRewardVideoAd(
    //     '948840227',
    //     customData: 'customData',
    //     userId: SPClassApplicaion.spProUserLoginInfo!.spProUserId.toString(),
    //   );
    // }


  }

  void spFunGetRecommended(){
    SPClassApiManager.spFunGetInstance().spFunSchemeList(context: context,queryParameters: {"fetch_type":'newest',"page":'1',"playing_way":'',"match_type":'足球'},spProCallBack: SPClassHttpCallBack(
        spProOnSuccess: (list){
          int index=-1;
          if(mounted){
            for(int i=0;i<list.spProSchemeList!.length;i++){
              if(list.spProSchemeList![i].spProIsBought=='1'||list.spProSchemeList![i].spProDiamond=='0'){
                continue;
              }
              index =i;
              break;
            }
            if(index!=-1){
              if(spFunIsLogin(context: context)){
                SPClassApiManager.spFunGetInstance().spFunSchemeDetail(
                    queryParameters: {"scheme_id":list.spProSchemeList![index].spProSchemeId},
                    context: context,spProCallBack:SPClassHttpCallBack<SPClassSchemeDetailEntity>(
                    spProOnSuccess: (value){
                      if(value.spProTask!=null&&value.spProTask?.spProIsShow=='1'){
                        SPClassTaskToast.spFunToast(context,value.spProTask!);
                      }
                      SPClassNavigatorUtils.spFunPushRoute(context,  SPClassSchemeDetailPage(value));
                    }
                ));
              }
            }
          }
        },
        onError: (value){

        }
    ));
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    myEventBus.cancel();
  }

}
